﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Lib.Paging;
using SDT.Lib.Common;
using System.IO;
using SDT.Lib.Helpers;
using SDT.Admin.Properties;
using SDT.Model;
using SDT.Admin.ViewModels;
namespace SDT.Admin.Controllers
{
	[RoleHelper(Roles = RoleSystem.Dictionary)]
    public class EventController : Controller
    {
        /// <summary>
        /// Created by: Vietlv
        /// Created date: 06/07/2011
        /// Description: Manage Event - Class Event controler;
        /// </summary>

        SDTDataContext eDataContext = new SDTDataContext();

        #region GET: /Event/ Index(int? Page)
        public ActionResult Index(int? page)
        {
			try
			{
				if (page == null) page = 1;
				string order = UserState.getUserStateFromRequest("article.order", "order", "ID").ToString();
				string orderDir = UserState.getUserStateFromRequest("article.orderDir", "orderDir", "desc").ToString();
				//int catID = Convert.ToInt32(UserState.getUserStateFromRequest("article.CatID", "CatID", 0));
				int currentHomeYN = Convert.ToInt32(UserState.getUserStateFromRequest("article.HomeYN", "HomeYN", 0));
				int currentPub = Convert.ToInt32(UserState.getUserStateFromRequest("article.PubStatus", "PubStatus", 0));
				string keyword = UserState.getUserStateFromRequest("article.Keyword", "Keyword", "").ToString();
				int pageSize = int.Parse(UserState.getUserStateFromRequest("article.pageSize", "PageSize", 20).ToString());

				var events = eDataContext.Events
					.Where(a => currentHomeYN > 0 ? a.HomeYN == (currentHomeYN == 1 ? true : false) : true)
					.Where(a => currentPub > 0 ? a.PubYN == (currentPub == 1 ? true : false) : true)
					.Where(a => (string.IsNullOrEmpty(keyword) ? true :
						(a.Title.ToLower().Contains(keyword.ToLower().Trim()) ||
						a.Description.ToLower().Contains(keyword.ToLower().Trim())
						)))
					.OrderBy(string.Format("{0} {1}", order, orderDir))
					.ToPagedList(page.Value - 1, pageSize);

				var homeYN = Utils.StringToDictionary(Settings.Default.ArticleHotStatus.ToString(), ",");
				var pubs = Utils.StringToDictionary(Settings.Default.ArticlePubStatus.ToString(), ",");

				ViewData["orderDir"] = orderDir;
				ViewData["order"] = order;

				return View(new EventIndexViewModel
				{
					Events = events,
					HomeYN = homeYN,
					PubStatus = pubs,
					CurrentHomeYN = currentHomeYN,
					CurrentPubStatus = currentPub,
					Keyword = keyword,
					ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.EventImagePreviewUrlPrefix
				});
			}
			catch (Exception ex)
			{ throw ex; }
                
        }
        #endregion

        #region GET: /Article/Details(int id)
        public ActionResult Details(int id)
        {
            var events = eDataContext.Events.Where(a => a.ID == id).SingleOrDefault();
            var imgRootUrl = Settings.Default.SiteRootUrl + Settings.Default.EventImagePreviewUrlPrefix;
            return View(new EventEditViewModel()
            {
                Event = events,
                ImageRootUrl = imgRootUrl
            });
        }
        #endregion

        #region GET: /Event/Create
		[RoleHelper(Roles = RoleSystem.Dictionary)]
        public ActionResult Create()
        {
            var imgRootUrl = Settings.Default.SiteRootUrl + Settings.Default.EventImagePreviewUrlPrefix;
            return View(new EventEditViewModel()
            {
                ImageRootUrl = imgRootUrl,
                Categories = ArticleManager.GetListCategory()
            });
        }
        #endregion

        #region POST: /Event/Create
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(EventEditViewModel a)
        {
            try
            {
                // TODO: Add insert logic here
                UpdateModel(a);
                a.Event.nArticle = 0;
                a.Event.Priority = 0;
                a.Event.AddDate = DateTime.Now;
                a.Event.AddBy = UserManager.GetUserId();
                eDataContext.Events.InsertOnSubmit(a.Event);
                eDataContext.SubmitChanges();
                //Image upload
                HttpPostedFileBase fileImage = Request.Files["ArticleImage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    a.Event.ImagePath = Path.GetFileName(fileImage.FileName);
                    Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.EventImageRootPath), "" + a.Event.ID);
                }
                eDataContext.SubmitChanges();
                var cats = eDataContext.ArticleCategories.ToList();
                if (cats != null)
                {
                    foreach (var c in cats)
                    {
                        var isSelected = Request["ArticleCategory." + c.ID] != null &&
                            Request["ArticleCategory." + c.ID].ToString().Equals("false") == false ? true : false;
                        if (isSelected == true)
                        {
                            EventArticleCategoryMap em = new EventArticleCategoryMap();
                            em.EventID = a.Event.ID;
                            em.CategoryID = c.ID;
                            eDataContext.EventArticleCategoryMaps.InsertOnSubmit(em);
                            eDataContext.SubmitChanges();
                        }
                    }
                }
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Event/Edit/5
		[RoleHelper(Roles = RoleSystem.Dictionary)]
        public ActionResult Edit(int id)
        {
            var events = eDataContext.Events.Where(a => a.ID == id).SingleOrDefault();
            return View(new EventEditViewModel()
            {
                Event = events,
                ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.EventImagePreviewUrlPrefix,
                Categories = ArticleManager.GetListCategory()
            });
        }
        #endregion

        #region POST: /Event/Edit/5
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(int id, EventEditViewModel a)
        {
            try
            {
                // TODO: Add update logic here
                a.Event = eDataContext.Events.Where(ar => ar.ID == id).SingleOrDefault();
                a.Event.ModifyBy = UserManager.GetUserId();
                a.Event.ModifyDate = DateTime.Now;
                UpdateModel(a);

                //image upload
                HttpPostedFileBase fileImage = Request.Files["ArticleImage"];
                if (fileImage != null && fileImage.FileName.Length > 0)
                {
                    //Delete old image
                    if (!string.IsNullOrEmpty(a.Event.ImagePath) && System.IO.File.Exists(string.Format("{0}\\{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.EventImageRootPath, "" + a.Event.ID + "_" + a.Event.ImagePath)))
                        Uploads.DeleteFile(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.EventImageRootPath, "" + a.Event.ID + "_" + a.Event.ImagePath));

                    //DO upload new image
                    a.Event.ImagePath = Path.GetFileName(fileImage.FileName);
                    Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.EventImageRootPath), "" + a.Event.ID);

                }
                var cats = eDataContext.ArticleCategories.ToList();
                if (cats != null)
                {
                    eDataContext.EventArticleCategoryMaps.DeleteAllOnSubmit(from dm in eDataContext.EventArticleCategoryMaps where dm.EventID == id select dm);
                    eDataContext.SubmitChanges();
                    foreach (var c in cats)
                    {
                        var isSelected = Request["ArticleCategory." + c.ID] != null &&
                            Request["ArticleCategory." + c.ID].ToString().Equals("false") == false ? true : false;
                        if (isSelected == true)
                        {
                            EventArticleCategoryMap em = new EventArticleCategoryMap();
                            em.EventID = a.Event.ID;
                            em.CategoryID = c.ID;
                            eDataContext.EventArticleCategoryMaps.InsertOnSubmit(em);
                            eDataContext.SubmitChanges();
                        }
                    }
                }
                eDataContext.SubmitChanges();

                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Event/Delete/5
       [RoleHelper(Roles = RoleSystem.Dictionary)]
        public ActionResult Delete(int id)
        {
            try
            {
                    var item = eDataContext.Events.Single(e => e.ID == id);
                    return View(item);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Event/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    var item = eDataContext.Events.Single(e => e.ID == id);
                    if (item != null)
                    {
                        Uploads.DeleteFile(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.EventImageRootPath,item.ID+"_"+ item.ImagePath));
                        eDataContext.EventArticleCategoryMaps.DeleteAllOnSubmit(from dm in eDataContext.EventArticleCategoryMaps where dm.EventID == id select dm);
                        eDataContext.ArticleEventMaps.DeleteAllOnSubmit(from dm in eDataContext.ArticleEventMaps where dm.EventID == id select dm);
                        eDataContext.Events.DeleteOnSubmit(item);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

    }
}
